﻿using Castle.MicroKernel.Registration;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Windsor.Installer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PwdMgr.Utility
{
    public class IOCContainer
    {
        private static IWindsorContainer _container;
        private static object _lock = new object();

        static IOCContainer()
        {
            Installers = new List<IWindsorInstaller>();
        }

        private static List<IWindsorInstaller> Installers { get; set; }

        public static void AddInstaller(IWindsorInstaller installer)
        {
            if (installer == null)
                throw new ArgumentNullException("installer");

            Installers.Add(installer);
        }

        public static void InitComponents()
        {
            try
            {
                if (_container == null)
                {
                    lock (_lock)
                    {
                        if (_container == null)
                        {
                            _container = new WindsorContainer();

                            AddInstaller(Configuration.FromXmlFile("Configs\\services.xml"));
                            _container.Install(
                                Installers.ToArray());
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static object Resolve(string key)
        {
            return _container.Resolve<object>(key);
        }

        public static T Resolve<T>(string key)
        {
            return _container.Resolve<T>(key);
        }
    }
}
